/**
 * This file is part of the dspace-poltman project http://www.poltman.com.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of DuraSpace DSpace license detailed in the LICENSE and NOTICE 
 * files at the root of the source tree and available online at
 * http://www.dspace.org/license/
 * 
 */
package com.poltman.dscentral.utils;

import java.util.Hashtable;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchResult;

import org.apache.log4j.Logger;

import com.poltman.dscentral.core.webappinit.WebAppInit;


/**
 * 
 * @author Zbigniew Ciok; z.ciok@poltman.com
 * @version $Revision: 1584 $
 * 
 */
public class LDAPLookup {
	
	private static Logger log = Logger.getLogger(LDAPLookup.class);

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String[] search(String userToSearch) {
		
		// 0: ldapEmail; 1: ldapGivenName; 2; ldapSurname; 3: ldapPhone; 
		String ldapAnswer[] = {"", "", "", ""};

		String ldapAdministrator = WebAppInit.getLdapAdministrator();   
		String ldapAdministratorPassword = WebAppInit.getLdapAdministratorPassword(); 
		String ldapProviderUrl = WebAppInit.getLdapProviderUrl();
		String ldapIdField = WebAppInit.getLdapIdField();
		String ldapSearchContext = WebAppInit.getLdapSearchContext();
		

		// attributes to search
		String ldapEmail = null;
		String ldapGivenName = null;
		String ldapSurname = null;
		String ldapPhone = null;

		Hashtable env = new Hashtable();
		env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(javax.naming.Context.PROVIDER_URL, ldapProviderUrl);
		env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
		env.put(javax.naming.Context.SECURITY_PRINCIPAL, "cn=" + ldapAdministrator);
		env.put(javax.naming.Context.SECURITY_CREDENTIALS, ldapAdministratorPassword);

		DirContext ctx = null;
		try {
			ctx = new InitialDirContext(env);

			String ldapEmailField = "mail";
			String ldapGivennameField = "givenName";
			String ldapSurnameField = "sn";
			String ldapPhoneField = "telephoneNumber";

			Attributes attributesToSearch = new BasicAttributes(true);
			attributesToSearch.put(new BasicAttribute(ldapIdField, userToSearch));

			String attlist[] = { ldapEmailField, 
								 ldapGivennameField, 
								 ldapSurnameField, 
								 ldapPhoneField };

			//look up attributes
			try {
				NamingEnumeration answer = ctx.search(ldapSearchContext, attributesToSearch, attlist);
				while (answer.hasMore()) {
					SearchResult sr = (SearchResult) answer.next();
					Attributes atts = sr.getAttributes();
					Attribute att;

					if (attlist[0] != null) {
						att = atts.get(attlist[0]);
						if (att != null) {
							ldapEmail = (String) att.get();
							ldapAnswer[0] = ldapEmail;
							log.info("ldapEmail = " + ldapEmail);
						}
					}

					if (attlist[1] != null) {
						att = atts.get(attlist[1]);
						if (att != null) {
							ldapGivenName = (String) att.get();
							ldapAnswer[1] = ldapGivenName;
							log.info("ldapGivenName = " + ldapGivenName);
						}
					}

					if (attlist[2] != null) {
						att = atts.get(attlist[2]);
						if (att != null) {
							ldapSurname = (String) att.get();
							ldapAnswer[2] = ldapSurname;
							log.info("ldapSurname = " + ldapSurname);
						}
					}

					if (attlist[3] != null) {
						att = atts.get(attlist[3]);
						if (att != null) {
							ldapPhone = (String) att.get();
							ldapAnswer[3] = ldapPhone;
							log.info("ldapPhone = " + ldapPhone);
						}
					}
				}
//			} catch (NamingException ne) {
			} catch (Exception e) {				
				log.info("LDAP attribute lookup, failed search ", e);
			}
//		} catch (NamingException e) {
		} catch (Exception e) {			
			log.info("LDAP authentication, failed authentication ", e);
		} finally {
			try {
				if (ctx != null) {
					ctx.close();
				}
			} catch (NamingException e) {
			}
		}
		return ldapAnswer;
	}
}
